package service

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"grpc/basic/global"
	__ "grpc/basic/proto"
	"log"
)

func (s *Server) EsList(_ context.Context, in *__.EsListReq) (*__.EsListResp, error) {
	if in.Page <= 0 {
		in.Page = 1
	}

	if in.Size <= 0 || in.Size >= 20 {
		in.Size = 10
	}
	var buf bytes.Buffer
	var r map[string]interface{}
	query := map[string]interface{}{}
	if in.Tage == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"title": in.Tage,
				},
			},
			"highlight": map[string]interface{}{
				"fields": map[string]interface{}{
					"types": "",
				},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}
	es := global.Ela
	// Perform the search request.
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("test"),
		es.Search.WithBody(&buf),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}
	var shon []*__.VideoList
	// Print the ID and document source for each hit.
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		//log.Printf(" * ID=%s, %s", hit.(map[string]interface{})["_id"], hit.(map[string]interface{})["_source"])
		now := hit.(map[string]interface{})["_source"].(map[string]interface{})
		fmt.Println(now)
		shon = append(shon, &__.VideoList{
			Username: now["username"].(string),
			Title:    now["title"].(string),
			Content:  now["content"].(string),
		})
	}

	return &__.EsListResp{
		List: nil,
	}, nil
}
